package com.scalar.chiptrack.adaptor.ikanos.utac;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.ShippedLot;
import com.scalar.chiptrack.adaptor.AssemblyLot;
import com.scalar.chiptrack.adaptor.utils.ParserResult;
import com.scalar.chiptrack.adaptor.utils.Parser;
import com.scalar.chiptrack.adaptor.utils.ParserFactory;
import com.scalar.chiptrack.adaptor.utils.CSVParserImpl;
import com.scalar.chiptrack.adaptor.utac.UTACShipStatus;
import com.scalar.chiptrack.adaptor.dao.ShippedLotDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.adaptor.dao.AssemblyAdaptorDAO;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.ScalarException;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Date;
import java.io.File;


/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: Nov 25, 2008
 * Time: 1:25:42 PM
 * To change this template use File | Settings | File Templates.
 */
public class UTACShipDataParser extends JobHandler implements AdaptorConstants
{
    private static Logger m_parserLogger= null;
    private String m_dataOutputDir      = null;

    private HashMap m_assyShipDataMap   = new HashMap();
    private HashMap m_assyYieldMap      = new HashMap();
    private HashMap m_ftShipDataMap     = new HashMap();


    public UTACShipDataParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = AdaptorUtils.getDataOutputDir( VENDOR_NAME_UTAC, LOCATION_TYPE_TEST );
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            m_parserLogger = AdaptorUtils.getDataParserLogger( m_dataOutputDir,VENDOR_NAME_UTAC );
            AssemblyAdaptorDAO.setLogger( m_parserLogger );
            ShippedLotDAO.setLogger( m_parserLogger );
            AdaptorUtils.setLogger( m_parserLogger );
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading/creating UTAC Ship Parser output directory from database, Exception: " + se);
            throw se;
        }
    }
    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main( String args[] ) throws Exception
    {
        try
        {
            new UTACShipDataParser().execute();
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    //Execute Method
   public void execute() throws Exception
   {
       AdaptorUtils.printHeader(VENDOR_NAME_UTAC + "WEB", CONSTANT_PARSER );

       File doneDestDir = new File( m_dataOutputDir + "/done" );

       File wipDataoutDir = new File( m_dataOutputDir );

       File[] fileList = wipDataoutDir.listFiles();

       if ( ( fileList == null ) || ( fileList.length <= 3 ) )
       {
           log( "No file found in directory: " + wipDataoutDir );
           throw new ScalarException( "No file found in directory: " + wipDataoutDir + "----\n\n" );
       }

       DBTransaction dbTransaction = null;
       ArrayList successFileList   = new ArrayList();
       boolean success             = false;

       try
       {
           for ( int i = 0; i < fileList.length; i++ )
           {
               if ( fileList[i].isDirectory() == true )
               {
                   continue;
               }

               if ( ( fileList[i].getName() != null ) && ( fileList[i].getName().trim().startsWith( UTACAdaptor.FILE_NAME_WEBSITE_YIELD ) || fileList[i].getName().trim().indexOf( UTACAdaptor.FILE_NAME_WEBSITE_YIELD) != -1 ) )
               {
                   parseDailyShipReport ( fileList[i].getAbsolutePath() );
                   /*ArrayList utacShipList = parseDailyShipReport( fileList[i].getAbsolutePath() );

                   if ( utacShipList != null )
                   {
                       getShippingDetails( utacShipList );
                   }*/
                   successFileList.add( fileList[i] );
               }
           }
       }
       catch ( Exception e )
       {
           success = false;
           log( "ERROR!! ERROR!! ERROR!! While parsing UTAC WebSite Yield Report and storing File " + e );
           e.printStackTrace();
           throw e;
       }
               
        try
        {
            // Save Assembly Ship Information
            if ( m_assyShipDataMap.isEmpty() == false )
            {
                log( " Updating Assembly Shiping Lot Information" );
                ShippedLotDAO.saveShippedLot( null, m_assyShipDataMap.values().iterator() );
            }
            success = true;
            m_assyShipDataMap.clear();
            m_assyShipDataMap = null;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update Assembly Shipping Lot information into database: " + se );
            throw se;
        }

       try
       {
           if ( !m_assyYieldMap.isEmpty() )
           {
               log(" Saving the assembly In transaction report information");

               AssemblyAdaptorDAO.saveAssemblyTransactionInQty( null, m_assyYieldMap.values().iterator() );
           }
       }
       catch (Exception e)
       {
           success = false;
            e.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update Assembly Yield Lot information into database: " + e );
            throw e;
       }
       try
        {
            // Save FT Ship Information
            if ( m_ftShipDataMap.isEmpty() == false )
            {
                log( " Updating FT Shiping Lot Information" );
                ShippedLotDAO.saveShippedLot( null, m_ftShipDataMap.values().iterator() );
            }
            success = true;
            m_ftShipDataMap.clear();
            m_ftShipDataMap = null;
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log( "ERROR!! ERROR!! ERROR!! Could not update FT Shipping Lot information into database: " + se );
            throw se;
        }

		// To Close the Drop Out Lots
      AdaptorDAO.closeDropOutLots( VENDOR_NAME_UTAC );

      // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
      AdaptorDAO.sendAllNotifications( VENDOR_NAME_UTAC, true, true, true );

      

      int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( UTACAdaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);

      // Update Adaptor_Run_Info table
      try
      {
            if ( success == true )
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, UTACAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
            }
      }
      catch ( ScalarException se )
      {
            success = false; //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, UTACAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log( "WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se );
            throw se;
       }
        // Move the successful files to 'done' directory
       if ( success )
       {
           AdaptorUtils.moveFilesToDone( successFileList, doneDestDir );
       }
   }//end of execute method

    private void parseDailyShipReport( String fileName ) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result     = null;
        ShippedLot shippedLot   = null;
        AssemblyLot assemblyLot = null;
        String lotNumber        = null;
        String partNumber       = null;
        String fablotNumber     = null;

        try
        {
            File detailWipFile = new File( fileName );
            if ( detailWipFile.exists() == false )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "\nParsing the file for ASSY/FT Ship Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for ASSY/FT Ship Report..." );

            Parser parser = ParserFactory.getCSVParser( detailWipFile, ',' );

            ((CSVParserImpl)parser).setHeaderRowIdx(0);
            ((CSVParserImpl)parser).setDataStartRowIdx(1);

            result = parser.parse();
            //System.out.println("result.getHeadings() = " + result.getHeadings());
            while ( result.next() )
            {
                partNumber = result.getString("CUSTPARTIN");
                fablotNumber = result.getString("CUSTLOTID");
                lotNumber   =  result.getString("LOTID");

                if ( lotNumber == null )
                {
                    lotNumber = fablotNumber;
                }
                String shipDate         = null;
                if ( partNumber != null && partNumber.trim().length() >0 && lotNumber != null && lotNumber.trim().length() > 0 )
                {
                    if ( result.getInt("T998-TFIN STAGESTARTQTY") > 0 )
                    {
                       log("In FT Shippping " + lotNumber );
                       if ( result.getDate("T998-TFIN STAGEENDTIME") != null)
                       {
                            shipDate = StringUtils.formatDateToString( result.getDate("T998-TFIN STAGEENDTIME", "MM/dd/yyyy hh:mm:ss aa"), "MM/dd/yyyy HH:mm" );
                       }
                       else
                       {
                           shipDate = StringUtils.formatDateToString( new Date(), "MM/dd/yyyy HH:mm" );
                       }
                                               
                       shippedLot = ( ShippedLot ) m_ftShipDataMap.get ( partNumber + lotNumber + fablotNumber + shipDate );

                       if ( shippedLot == null )
                       {
                            shippedLot = new ShippedLot(VENDOR_NAME_UTAC, LOCATION_TYPE_TEST );
                            m_ftShipDataMap.put( partNumber + lotNumber + fablotNumber + shipDate, shippedLot );
                       }

                       int quantity = 0;
                       if ( shippedLot.getShipQty() != null )
                       {
                           try
                           {
                               quantity = Integer.parseInt( shippedLot.getShipQty() );
                           }
                           catch ( NumberFormatException ignore )
                           {
                               quantity = 0;
                           }
                           try
                           {
                               quantity += result.getInt("T998-TFIN STAGESTARTQTY");
                           }
                           catch ( NumberFormatException ignore )
                           {
                               quantity = 0;
                           }
                       }
                       else
                       {
                           try
                           {
                               quantity = result.getInt("T998-TFIN STAGESTARTQTY");
                           }
                           catch ( NumberFormatException ignore )
                           {
                               quantity = 0;
                           }
                       }

                       if ( quantity > 0 )
                       {
                           shippedLot.setLotNumber( lotNumber );
                           shippedLot.setPartNumber( partNumber );
                           shippedLot.setShipDate( shipDate );
                           shippedLot.setShipQty( quantity + "" );
                           shippedLot.setFabLotNumber( fablotNumber );
                           shippedLot.setProcessType( LOCATION_TYPE_FT );
                       }
                   }

                   //ASSEMBLY YIELD
                   if ( result.getInt("P200-DBANK STAGESTARTQTY") > 0 )
                   {
                       assemblyLot = (AssemblyLot) m_assyYieldMap.get( partNumber + fablotNumber + lotNumber );

                       if (assemblyLot == null)
                       {
                           assemblyLot = new AssemblyLot( VENDOR_NAME_UTAC, LOCATION_TYPE_ASSEMBLY);
                           m_assyYieldMap.put( partNumber + fablotNumber + lotNumber , assemblyLot );
                       }

                       int assyQtyIn = 0;
                       if ( assemblyLot.getQtyIn() != null)
                       {
                           try
                           {
                               assyQtyIn = Integer.parseInt( assemblyLot.getQtyIn() );
                           }
                           catch ( NumberFormatException ignore )
                           {
                               assyQtyIn = 0;
                           }

                           assyQtyIn += result.getInt("P200-DBANK STAGESTARTQTY");

                       }
                       else
                       {
                           assyQtyIn = result.getInt("P200-DBANK STAGESTARTQTY");
                       }
                       if ( assyQtyIn > 0 )
                       {
                           assemblyLot.setQtyIn( assyQtyIn +"");
                           assemblyLot.setDateIn( StringUtils.formatDateToString( result.getDate("P200-DBANK STAGEENDTIME", "MM/dd/yyyy hh:mm:ss aa"), "MM/dd/yyyy HH:mm" ) );
                           assemblyLot.setLotNumber( lotNumber );
                           assemblyLot.setDeviceName( partNumber );
                           assemblyLot.setFabLotNumber( fablotNumber );
                       }
                   }

                   //ASSEMBLY SHIPPING 
                   if ( result.getInt("A990-AFIN STAGESTARTQTY") > 0 )
                   {
                       log("In Assembly Shippping " + lotNumber );
                       if ( result.getDate("A990-AFIN STAGEENDTIME" ) != null )
                       {
                           shipDate = StringUtils.formatDateToString( result.getDate("A990-AFIN STAGEENDTIME", "MM/dd/yyyy hh:mm:ss aa"), "MM/dd/yyyy HH:mm" );
                       }
                       else
                       {
                           shipDate = StringUtils.formatDateToString( new Date(), "MM/dd/yyyy HH:mm" );
                       }
                       shippedLot = ( ShippedLot ) m_assyShipDataMap.get ( partNumber + fablotNumber + lotNumber + shipDate );

                       if ( shippedLot == null )
                       {
                           shippedLot = new ShippedLot(VENDOR_NAME_UTAC, LOCATION_TYPE_ASSEMBLY);
                           m_assyShipDataMap.put( partNumber + fablotNumber + lotNumber + shipDate, shippedLot );
                       }

                       int quantity = 0;
                       if ( shippedLot.getShipQty() != null )
                       {
                           try
                           {
                               quantity = Integer.parseInt( shippedLot.getShipQty() );
                           }
                           catch ( NumberFormatException ignore )
                           {
                               quantity = 0;
                           }
                           try
                           {
                               quantity += result.getInt("A990-AFIN STAGESTARTQTY");
                           }
                           catch ( NumberFormatException ignore )
                           {
                               quantity = 0;
                           }
                       }
                       else
                       {
                           try
                           {
                               quantity = result.getInt("A990-AFIN STAGESTARTQTY");
                           }
                           catch ( NumberFormatException ignore )
                           {
                               quantity = 0;
                           }
                       }

                       if ( quantity > 0 )
                       {
                           shippedLot.setLotNumber( lotNumber );
                           shippedLot.setPartNumber( partNumber );
                           shippedLot.setShipDate( shipDate );
                           shippedLot.setShipQty( quantity + "" );
                           shippedLot.setFabLotNumber( fablotNumber );
                           shippedLot.setProcessType( LOCATION_TYPE_ASSEMBLY );
                       }
                   }
                }
            }
        }
        catch(Exception ex)
        {
            System.out.println("ERROR!!!ERROR!!! While Parsing the UTAC Assy/FT Ship Report");
            ex.printStackTrace();
            throw ex;

        }
    }
    /*private ArrayList parseDailyShipReport( String fileName ) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ArrayList shipList              = new ArrayList();
        String line                     = null;

        try
        {
            File detailShipFile = new File( fileName );
            if ( detailShipFile.exists() == false )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            log( "\nFound " + fileName );
            log( "\nParsing the file for ASSY/FT Ship Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for ASSY/FT Ship Report..." );

            BufferedReader reader = new BufferedReader( new FileReader( detailShipFile ) );
            reader.readLine();  // Read out <Report Name> Line
             while ( ( line = reader.readLine() ) != null  && line.length() > 0 )
            {
                UTACShipStatus shipStatus = new UTACShipStatus();

                line = line.replaceAll( "\"", "" );

                String[] token = line.split( "," );

                for (int x = 0; x < token.length; x++)
                {
                    if (token[x] != null && token[x].trim().length() > 0)
                    {
                        switch (x)
                        {
                            case 0:
                                    shipStatus.setCustLotNo(token[x].trim() );
                                    break;
                            case 1:
									shipStatus.setVendorLotNo(token[x].trim() );
                                    break;
                            case 2:
                                    shipStatus.setDeviceName(token[x].trim() );
                                    break;
                            //3 to 8 not required
                            case 24:
                                    shipStatus.setAssyOutQty( "0".equalsIgnoreCase(token[x].trim() ) ? null :  token[x].trim() ); //A900 AFIN
                                    break;
                            case 25:
                                    shipStatus.setAssyShipDate( token[x].trim().split(" ")[0] );
                                    break;
                            //26
                            case 27:
                                    shipStatus.setFtOutQty("0".equalsIgnoreCase(token[x].trim() ) ? null :  token[x].trim() ); //T998 TFIN
                                    break;
                            case 28:
                                    shipStatus.setFtShipDate( token[x].trim().split(" ")[0] );
                                    break;
                            //Remaing Fileds Not Required
                         }

                    }

                }
                if (shipStatus.getDeviceName() != null && shipStatus.getDeviceName().length() > 0 )
				{
                    shipList.add( shipStatus );
                }
            }

            try
            {
                if ( reader != null )
                {
                   reader.close();
                }
            }
            catch(IOException ignore)
            {

            }

        }
        catch ( Exception ex )
        {   System.out.println("ERROR!!!ERROR!!! While Parsing the UTAC ASSY/FT Shippment Sheet");
            ex.printStackTrace();
            throw ex;
        }

        return shipList;

    }*/ // end of prase Daily FG ShipReport method


   /* private void getShippingDetails(ArrayList shippingDataList) throws Exception
    {
       if ( shippingDataList == null || shippingDataList.size() == 0 )
       {
            return;
       }
       UTACShipStatus shipStatus  = null;
       String partNumber           = null;
       String lotNumber            = null;
       ShippedLot shippedLot       = null;
       String fabLotNumber         = null;

       try
       {
           Iterator iterator = shippingDataList.iterator();

           while ( iterator.hasNext() )
           {
               shipStatus = (UTACShipStatus) iterator.next();

               lotNumber    = shipStatus.getVendorLotNo();
               partNumber   = shipStatus.getDeviceName();
               fabLotNumber = shipStatus.getCustLotNo();

               //FT SHIP
               if ( shipStatus.getFtOutQty() != null )
               {
                   log("In FT Shippping " + lotNumber );
                   shippedLot = ( ShippedLot ) m_ftShipDataMap.get ( partNumber + lotNumber + fabLotNumber + shipStatus.getFtShipDate() );

                   if ( shippedLot == null )
                   {
                        shippedLot = new ShippedLot(VENDOR_NAME_UTAC, LOCATION_TYPE_TEST );
                        m_ftShipDataMap.put( partNumber + lotNumber + fabLotNumber + shipStatus.getFtShipDate(), shippedLot );
                   }

                   int quantity = 0;
                   if ( shippedLot.getShipQty() != null )
                   {
                       try
                       {
                           quantity = Integer.parseInt( shippedLot.getShipQty() );
                       }
                       catch ( NumberFormatException ignore )
                       {
                           quantity = 0;
                       }
                       try
                       {
                           quantity += Integer.parseInt( shipStatus.getFtOutQty() );
                       }
                       catch ( NumberFormatException ignore )
                       {
                           quantity = 0;
                       }
                   }
                   else
                   {
                       try
                       {
                           quantity = Integer.parseInt( shipStatus.getFtOutQty() );
                       }
                       catch ( NumberFormatException ignore )
                       {
                           quantity = 0;
                       }
                   }

                   if ( quantity > 0 )
                   {
                       shippedLot.setLotNumber( lotNumber );
                       shippedLot.setPartNumber( partNumber );
                       shippedLot.setShipDate( shipStatus.getFtShipDate() );
                       shippedLot.setShipQty( quantity + "" );
                       shippedLot.setFabLotNumber( fabLotNumber );
                       shippedLot.setProcessType( LOCATION_TYPE_FT );
                   }
               }
               //CP SHIPPING
               if ( shipStatus.getAssyOutQty() != null )
               {
                      log("In Assembly Shippping " + lotNumber );
                   shippedLot = ( ShippedLot ) m_assyShipDataMap.get ( partNumber + fabLotNumber + lotNumber + shipStatus.getAssyShipDate() );

                   if ( shippedLot == null )
                   {
                        shippedLot = new ShippedLot(VENDOR_NAME_UTAC, LOCATION_TYPE_ASSEMBLY);
                        m_assyShipDataMap.put( partNumber + fabLotNumber + lotNumber + shipStatus.getAssyShipDate(), shippedLot );
                   }

                   int quantity = 0;
                   if ( shippedLot.getShipQty() != null )
                   {
                       try
                       {
                           quantity = Integer.parseInt( shippedLot.getShipQty() );
                       }
                       catch ( NumberFormatException ignore )
                       {
                           quantity = 0;
                       }
                       try
                       {
                           quantity += Integer.parseInt( shipStatus.getAssyOutQty() );
                       }
                       catch ( NumberFormatException ignore )
                       {
                           quantity = 0;
                       }
                   }
                   else
                   {
                       try
                       {
                           quantity = Integer.parseInt( shipStatus.getAssyOutQty() );
                       }
                       catch ( NumberFormatException ignore )
                       {
                           quantity = 0;
                       }
                   }

                   if ( quantity > 0 )
                   {
                       shippedLot.setLotNumber( lotNumber );
                       shippedLot.setPartNumber( partNumber );
                       shippedLot.setShipDate( shipStatus.getAssyShipDate() );
                       shippedLot.setShipQty( quantity + "" );
                       shippedLot.setFabLotNumber( fabLotNumber );
                       shippedLot.setProcessType( LOCATION_TYPE_ASSEMBLY );
                   }
               }
           }
        }
        catch(Exception e )
        {
            e.printStackTrace();
            log("Exception while geting UTAC Shipping inforamtion" + e);
            throw  e;
        }
    } */
    
   private static void log( String message )
    {

        if ( message == null ) return;

        if ( m_parserLogger != null )
        {
            synchronized ( m_parserLogger )
            {
                m_parserLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}
